package com.xl333.util;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * @Date 2019/11/18
 * @Author danger
 */
public class ReflectUtil {

    /**
     * 设置对像属性值
     * @param o
     * @param fieldName
     * @param value
     */
    public static void setFieldValue(Object o, String fieldName, Object value){
        Class cls = o.getClass();
        try{
            Field field = cls.getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(o, value);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 获取属性值
     * @param o
     * @param fieldName
     * @return
     */
    public static Object getFieldValue(Object o, String fieldName){
        Class cls = o.getClass();
        try{
            Field field = cls.getDeclaredField(fieldName);
            field.setAccessible(true);
            return field.get(o);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据无参构造函数创建一个实例
     * @param cls
     * @param <T>
     * @return
     * @throws NoSuchMethodException
     * @throws InstantiationException
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     * @throws InvocationTargetException
     */
    public static <T> T newInstance(Class cls)
            throws NoSuchMethodException,InstantiationException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException {
        Constructor<T> constructor = cls.getConstructor();
        return constructor.newInstance();
    }

}
